package site.qjdb.config;

import site.qjdb.exception.ParamException;
import site.qjdb.exception.WarningException;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "site.qjdb")
public class GlobalExceptionConfig {
    @Value("${spring.profiles.active}")
    private String env;

    /**
     * JSR303校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindResult = e.getBindingResult();
        Map<String, Object> map = new HashMap<>();
        for(FieldError error : bindResult.getFieldErrors()) {
            map.put(error.getField(), error.getDefaultMessage());
        }
        return new CommonResult(ResponseCode.PARAM_ERROR, map);
    }

    /**
     * 参数异常
     */
    @ExceptionHandler(ParamException.class)
    public CommonResult paramException(Exception e) {
        return new CommonResult(ResponseCode.PARAM_ERROR, e.getMessage());
    }





    @ExceptionHandler(WarningException.class)
    public CommonResult warningException(WarningException e) {
        log.warn("warning：" + CommonUtils.formatNow() , e);
        return new CommonResult(ResponseCode.WARNING, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public CommonResult Exception(Exception e) {
        log.error("全局异常捕获 " + CommonUtils.formatNow(), e);
        // 测试环境返回报错详细信息
        if(!"prd".equals(env)) {
            return new CommonResult(ResponseCode.ERROR, e.getMessage());
        }
        return new CommonResult(ResponseCode.ERROR);
    }
}
